package view.models;

import java.util.Date;
import java.text.DateFormat;
import java.util.Observable;
import java.util.Observer;
import javax.swing.table.AbstractTableModel;
import domain.Copy;
import domain.Library;
import domain.Loan;

@SuppressWarnings("serial")
public class LoanTable extends AbstractTableModel implements Observer, LoanTableInterface {
	Library lib = Library.getInstance();
	DateFormat localizeDate = DateFormat.getDateInstance();
	private String[] columnNames = new String[]{"Exemplar",
			"Titel", "Ausgeliehen an", "Ausgeliehen seit", "Status"};

	public LoanTable() {
		for (Loan l : lib.getLoans()) {
			l.addObserver(this);
			l.getCopy().addObserver(this);
		}
		
		lib.addObserver(this);
	}

	@Override
	public int getColumnCount() {
		return columnNames.length;
	}

	@Override
	public int getRowCount() {
		return lib.getLoans().size();
	}

	@Override
	public String getColumnName(int col) {
		return columnNames[col];
	}

	@Override
	public Object getValueAt(int row, int col) {
		Loan loan = lib.getLoans().get(row);
		switch(col){
			case 0:
				return loan.getCopy().getInventoryNumber();
			case 1:
				return loan.getCopy().getTitle().toString();
			case 2:
				return loan.getCustomer().getSurname() + " " + loan.getCustomer().getName();
			case 3:
				return loan.getPickupDate().getTime();
			case 4:
				return LoanStatus.getInstanceOf(loan);
		}
		return null;
	}

	@Override
	public void update(Observable arg0, Object arg1) {
		for (Loan l : lib.getLoans()) {
			l.addObserver(this);
		}
		lib.addObserver(this);
		fireTableDataChanged();

	}

	public Copy getCopyAt(int row) {
		return lib.getLoans().get(row).getCopy();
	}

	public Loan getLoanAt(int row) {
		return lib.getLoans().get(row);
	}

	// Ohne das weiss die Tabelle nicht welche klasse dahinter steckt (bei
	// boolean wird automatisch checkbox erzeugt!)
	@SuppressWarnings({"rawtypes", "unchecked"})
	public Class getColumnClass(int c) {
		switch(c){
			case 0:
				return Integer.class;
			case 3:
				return Date.class;
			case 4:
				return LoanStatus.class;
			default:
				return String.class;
		}
	}

	public void disbandObservers() {
		lib.deleteObserver(this);
		for (Loan l : lib.getLoans()) {
			l.deleteObserver(this);
			l.getCopy().deleteObserver(this);
		}
	}

}
